$('#stop_journey').hide();
$('#journeyUploadMedia').hide();
var pos_id;
var	url_satellite='http://{s}.tiles.mapbox.com/v3/dennisl.map-6g3jtnzm/{z}/{x}/{y}.png',
	url_mapQuest = 'http://otile3.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.jpg',
	url_OSMtransport = 'http://{s}.tile2.opencyclemap.org/transport/{z}/{x}/{y}.png',
	url_OSMstandart = 'http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png',

	transport = new L.TileLayer(url_OSMtransport, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	standart = new L.TileLayer(url_OSMstandart, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	satellite = new L.TileLayer(url_satellite, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	mapQuest = new L.TileLayer(url_mapQuest, {minZoom: 12, maxZoom: 18,
		attribution: ''}),
	mapQuest2 = new L.TileLayer(url_mapQuest, {minZoom: 9, maxZoom:15});
 
var baseMaps = {
	'OSM Transport':transport,
	'MapQuest':mapQuest,
	'OSM Standart':standart,
	'Mapbox Satellite': satellite
};

var map = new L.Map('MainMap', {
	    layers: [mapQuest],
	    center: [10.772113,106.657832],
	    zoom: 16,
		zoomControl: false,
		contextmenu: true,
		contextmenuWidth: 160,
		contextmenuItems: [{
		text: 'Tìm đường từ đây',
	}, '-', {
		text: 'Tìm đường đến đây',
	}, {
		text: 'Chia sẻ địa điểm này',
	}, {
		text: 'Lưu lại vị trí này',
	}]
});

map.locate({setView: true, maxZoom: 16});
function onLocationFound(e) {
    var radius = e.accuracy / 2;
    L.marker(e.latlng).addTo(map)
        .bindPopup("You are within " + radius + " meters from this point").openPopup();
    L.circle(e.latlng, radius).addTo(map);
}
map.on('locationfound', onLocationFound);

map.addControl(L.control.zoom({position: 'topright'}));

// add location control to global name space for testing only
// on a production site, omit the "lc = "!
lc = L.control.locate({
    follow: true,
    keepCurrentZoomLevel: true,
    circlePadding: [100, 100],
    position: 'topright'
}).addTo(map);

map.on('startfollowing', function() {
    map.on('dragstart', lc._stopFollowing, lc);
}).on('stopfollowing', function() {
    map.off('dragstart', lc._stopFollowing, lc);
});


var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
//Set the title to show on the polygon button
L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a sexy polygon!';

var drawControl = new L.Control.Draw({
	position: 'topright',
	draw: {
		polyline	: false,
		polygon		: false,
		rectangle	: false,
		circle		: false,
		marker		: true
	},
	edit: {
		featureGroup: drawnItems,
		edit: false
	}
});
map.addControl(drawControl);

map.on('draw:created', function (e) {
	var type = e.layerType,
		layer = e.layer;

	if (type === 'marker') {
		layer.bindPopup('A popup!');
	}

	drawnItems.addLayer(layer);
});

map.on('draw:edited', function (e) {
	var layers = e.layers;
	var countOfEditedLayers = 0;
	layers.eachLayer(function(layer) {
		countOfEditedLayers++;
	});
	console.log("Edited " + countOfEditedLayers + " layers");
});

var snapshot = document.getElementById('snapshot');
function doImage(err, canvas) {
    var img = document.createElement('img');
    var dimensions = map.getSize();
    img.width = dimensions.x;
    img.height = dimensions.y;
    img.src = canvas.toDataURL();
    snapshot.innerHTML = '';
    snapshot.appendChild(img);
}
leafletImage(map, doImage);

//=====================================
// Point
//=====================================
	
var gs = {
	get_id: '/point/ajax_get',
	insert: '/point/ajax_insert',
	update: '/point/ajax_update',
	remove: '/point/ajax_remove',
	insert_url: '/point/insert_url'
};

// Configure map
var map, user;
var markers = [];

var poiIcon = L.Icon.extend({
    options: {
        iconSize: [22,32],
        iconAnchor: [-20,0],
        shadowUrl: 'public/plugin/icons/poi_shadow.png',
        shadowSize: [22,13],
        shadowAnchor: [-31,-19],
        popupAnchor: [32,-2]
    }
});

var blackIcon = new poiIcon({iconUrl:'public/plugin/icons/poi_black.png'});
var redIcon   = new poiIcon({iconUrl:'public/plugin/icons/poi_red.png'});
var treeIcon  = new poiIcon({iconUrl:'public/plugin/icons/tree_green.png',shadowUrl:'public/plugin/icons/tree_shadow.png'});

// Load user points
//loadPoints();

//Drag & Drop
$(".drag").draggable({
	helper: 'clone',
	containment: 'map',
	start: function(evt, ui) {
		$('#box').fadeTo('fast', 0.6, function() {});
	},
	stop: function(evt, ui) {
		$('#box').fadeTo('fast', 1.0, function() {});
		
		var options = {
			posid: '',
			pid: '',
			type: ui.helper.attr('type'),
			icon: eval(ui.helper.attr('type') + 'Icon'),
			draggable: true
		};
		
		insertPoint(
			map.containerPointToLatLng([ui.offset.left, ui.offset.top]),
			options
		);
	}
});		

//GET points
function loadPoints() {
	var postData = {
		posid: '30',
		pid: '',
		type: '',
		lat: '',
		lng: ''
	}
	$.ajax({
		type: "POST",
		url: '/point/ajax_get',
		data: postData,
		//TODO: Error handling
		success: function(data){
	
			// Remove all markers
			for(i=0;i<markers.length;i++) {
				map.removeLayer(markers[i]);
			}
			markers = [];
		
			// Add markers
			for(i=0;i<data.length;i++) {
			
				var ftr = data[i];
	
				var options = {
					posid: ftr.position_id,
					pid: ftr.coordinate_id,
					type: ftr.type,
					icon: eval(ftr.type + 'Icon'),
					draggable: true
				};
				
				var point = L.marker([ftr.latitude,ftr.longtitude],options).addTo(map);
				point.bindPopup(
					'<a class="btn btn-sm btn-primary"  onClick="upLoadMedia(\'' + point.options.posid 
						+ '\');">Add Media</a><a class="btn btn-sm btn-warning" onClick="deletePoint(\'' + point.options.posid 
						+ '\');" href="#">Remove Me!</a>',
					{
						closeButton: false
					}
				);
	
				point.on('dragend', function(evt){
					updatePoint(evt.target);
				}); 
		
				markers.push(point);
			}
		}
	});
}

// INSERT point
function insertPoint(position,options) {
	var postData = {
		posid: '',
		pid: '',
		type: options.type,
		lat: position.lat,
		lng: position.lng
	}
	
	$.ajax({
		type: "POST",
		url: '/point/ajax_insert',
		data: postData,
		success: function(data) {	
			options.posid = data.position_id;
			options.pid   = data.coordinate_id;
			
			var point = L.marker(position,options).addTo(map);
			point.on('dragend', function(evt){
				updatePoint(point);
			});
			markers.push(point);

			point.bindPopup(
					'<a class="btn btn-sm btn-primary"  onClick="upLoadMedia(\'' + point.options.posid 
					+ '\');">Add Media</a><a class="btn btn-sm btn-warning" onClick="deletePoint(\'' + point.options.posid 
					+ '\');" href="#">Remove Me!</a>',
				{
					closeButton: false
				}
			);
		}
	});
}

// UPDATE point
function updatePoint(point) {

	var postData = {
		posid: point.options.posid,
		pid: point.options.pid,
		type: point.options.type,
		lat: point.getLatLng().lat,
		lng: point.getLatLng().lng
	}
	
	$.ajax({
		type: "POST",
		url: '/point/ajax_insert',
		data: postData,
		success: function(xml) {	
		}
	});
}

// DELETE point
function deletePoint(posid) {
	var point;
	for(i=0;i<markers.length;i++) {
		if(markers[i].options.posid == posid) {
			point = markers[i];
			map.removeLayer(markers[i]);
			markers.splice(i, 1);
		}
	}

	var postData = {
		posid: point.options.posid,
		pid: point.options.pid,
		type: point.options.type,
		lat: point.getLatLng().lat,
		lng: point.getLatLng().lng
	}
	
	$.ajax({
		type: "POST",
		url: '/point/ajax_remove',
		data: postData,
		success: function(xml) {	
		}
	});
}
//Upload media
function upLoadMedia(posid){
	
	$('#modal').modal('show');
	pos_id = posid;
}
function saveMedia(){
 var url = $('#url').val();
 var name = $('#name-text').val();
 $.ajax({
		type: "POST",
		url: '/point/insert_url',
		data: {
			link : url,
			posid : pos_id,
			name :name
		},
		success: function(xml) {	
			$('#modal').modal('hide');
			
		}
	});
}
// Take Journey
IS_NEW_JOURNEY=true;
IS_TAKE_JOURNEY=false;
var journey_id;
function  onLocationFound(e) {
	var marker =  L.marker(e.latlng).addTo(map);
	//console.log(e.latlng);
	var lat = (e.latlng.lat);
	var lng = (e.latlng.lng);
	marker.setLatLng([lat, lng]).update(); 
	//setInterval(function () {alert(e.latlng.lat)}, 3000);
	var postData = {
		flag: 0,
		lat: 0,
		lng: 0
	}
	setInterval(function () {
		if(IS_TAKE_JOURNEY){
			postData.flag = IS_NEW_JOURNEY ? 0 : postData.flag;
			postData.lat  = e.latlng.lat;
			postData.lng  = e.latlng.lng; 
			
			$.ajax({
				url: '/journey/ajax_insert',
				type: "POST",
				data: postData,
				success: function(data) {
					if(postData.flag == 0){
						postData.flag = data.position_id;
						IS_NEW_JOURNEY = false;
						journey_id = postData.flag;
					}
				},
				error: function(e) {}
			});
		}
	 }, 3000);
}
//map.on('locationfound', onLocationFound);
$('#snap').click(function(){
	
		IS_TAKE_JOURNEY = true;
		$('#stop_journey').show();
		$('#journeyUploadMedia').show();
		$('#snap').hide();
		//alert("You must to go to your location to do this function");
		map.on('locationfound', onLocationFound);
});
$('#stop_journey').click(function(){
		IS_NEW_JOURNEY = true;
		IS_TAKE_JOURNEY = false;
		//$('#stop_journey').show();
		$('#journey_modal').modal('show');
		$('#journeyUploadMedia').hide();
	
});
function saveJourney(){
	var name = $('#journey_name').val();
	var note = $('#note-text').val();
	//alert(journey_id);
	$.ajax({
		type: "POST",
		url: '/journey/save_journey',
		data: {
			name : name,
			note : note,
			journey_id : journey_id
		},
		success: function(xml) {	
			$('#stop_journey').hide();
			$('#snap').show();
			$('#journey_modal').modal('hide');
		}
	});
}
	function deleteJourney(){
		//alert(journey_id);
		var conf = confirm("Are you sure to cancel to save this journey!!");
		if (conf==true){
			$.ajax({
				type: "POST",
				url: '/journey/delete_journey',
				data: {
					journey_id : journey_id
				},
				success: function(xml) {	
					$('#journey_modal').modal('hide');
				}
			});
		}
		
}
function upLoadMediaForJourney(){
	alert("drag and drop icon and add media");
	
};	
//map.on('click', function(e) {
    //alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng)
//});
